package com.weige.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: wei
 * @date: 2022-11-12 16:30
 * @description: 自定义全局过滤器
 */
@Component
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    /**
     * @param exchange 对request,response对象封装
     * @param chain    过滤器链,可以将过滤请求委托给下一个过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //  获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //  获取authorization参数
        String authorization = queryParams.getFirst("authorization");
        //  校验
        if ("admin".equals(authorization)) {
            // 放行
            return chain.filter(exchange);
        }
        //  拦截
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
